package com.cxm.helper.consumer;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cxm.helper.pojo.Message;
import com.cxm.helper.service.MessageService;
import com.cxm.helper.util.constant.RabbitMqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: chenximeng
 * @date: 2022/12/2 17:41
 */
@Slf4j
@Component
public class MessageConsumer {

    @Autowired
    MessageService messageService;

    @RabbitHandler
    @RabbitListener(queues = RabbitMqConstant.MESSAGE_SAVE_QUEUE)
    public void saveMessage(String content) {
        Message message = JSONUtil.toBean(content, Message.class);
        log.info("mq save msg receive message:{}", content);
        QueryWrapper<Message> wrapper = new QueryWrapper<>();
        wrapper.eq("send_user_id", message.getSendUserId());
        wrapper.eq("receive_user_id", message.getReceiveUserId());
        wrapper.eq("business_type", message.getBusinessType());
        wrapper.eq("business_id", message.getBusinessId());
        wrapper.eq("message_type", message.getMessageType());
        if (messageService.getOne(wrapper) != null) {
            log.info("repeat message");
            return;
        }
        messageService.save(message);
        log.info("mq save finish");
    }

    @RabbitHandler
    @RabbitListener(queues = RabbitMqConstant.MESSAGE_READ_QUEUE)
    public void readMessage(String content) {
        List<Long> msgIds = JSONUtil.toList(JSONUtil.parseArray(content), Long.class);
        log.info("mq read msg:{}", msgIds);
        Message message = new Message();
        message.setStatus(1);
        messageService.update(message, new QueryWrapper<Message>().in("id", msgIds));
        log.info("mq read finish");
    }

}
